package com.zhixinsou.wuyang.process;

import com.alibaba.fastjson.JSON;
import com.zhixinsou.wuyang.model.AnalysisReport;
import com.zhixinsou.wuyang.model.SheetModel;
import com.zhixinsou.wuyang.util.FileUtil;
import com.zhixinsou.wuyang.util.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProcessThinkEquity {
    public static List<AnalysisReport> getAnalysisReportPageInfo(String filePath) {
        List<AnalysisReport> reports = new ArrayList<>();
        int startPage = 1;
        File file = new File(filePath);
        String[] lines = FileUtil.pdfReader(file, startPage, startPage).split("\r\n");
        Pattern pattern = Pattern.compile("([0-9]+)\\s-\\s([0-9]+)$");
        while (lines.length > 1 && lines[0].equals("Table of Contents")) {
            for (String line : lines) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    AnalysisReport report = new AnalysisReport();
                    report.setFilePath(filePath);
                    report.setFileName(file.getName());
                    report.setStartPage(Integer.parseInt(matcher.group(1)));
                    report.setEndPage(Integer.parseInt(matcher.group(2)));
                    report.setBrokerName("ThinkEquity Partners");
                    
                    reports.add(report);
                }
            }

            startPage++;
            lines = FileUtil.pdfReader(filePath, startPage, startPage).split("\r\n");
        }
        return reports;
    }

    public static void getAnalysisReportDetail(AnalysisReport report) {
        Pattern patternVersion = Pattern.compile("Thinkequity_File\\s([0-9]+)");
        Matcher matcher = patternVersion.matcher(report.getFileName());
//        System.out.println(report.getFileName());
        if (matcher.find()) {
            int index = Integer.parseInt(matcher.group(1));
//            System.out.println(index);
            getAnalysisReportDetailVersion(report);
//            if(year < 2007)
//                getAnalysisReportDetailVersion(report);
//            else{
//                if(year == 2007 && version < 5)
//                    getAnalysisReportDetailVersion(report);
//                else
//                    getAnalysisReportDetailVersion2(report);
//            }
        }
    }

    public static void getAnalysisReportDetailVersion(AnalysisReport report) {
        String content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage());
        String[] lines = content.split("\r\n");

        //Date
        Pattern patternDate = Pattern.compile("(January|February|March|April|May|June|July|August|September|October|November|December){1}\\s*[0-9]+\\S\\s*[0-9]{4}");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherDate = patternDate.matcher(line);
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }

        //Ticker and Rating
        content = FileUtil.pdfReaderWithFontsAndColor(report.getFilePath(), report.getStartPage(), report.getStartPage());
        lines = content.split("\r\n");
        Pattern patternTicker = Pattern.compile("(Arial,Bold\\]<17\\.0>|ArialMT\\-Bold\\]<17\\.0>).*\\(([A-Z]+)\\)");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherTicker = patternTicker.matcher(line);
            if (matcherTicker.find()) {
                System.out.println("The ticker line is :" + lines[i]);
                report.setTicker(matcherTicker.group(2));
                Pattern patternRating = Pattern.compile("(Arial,Bold\\]<12\\.0>|ArialMT\\-Bold\\]<12\\.0>)(.*)");
                for(int j = i + 1; j < lines.length; j++){
                    Matcher matcherRating = patternRating.matcher(lines[j]);
                    if(matcherRating.find()){
                        String orginRating = matcherRating.group(2);
                        System.out.println("The rating line is " + orginRating);
                        if(orginRating.contains("[")){
                            int end = orginRating.indexOf("[");
                            report.setRating(orginRating.substring(0,end));
                        }
                        else{
                            report.setRating(orginRating);
                        }
                        break;
                    }
                }
                break;
            }
        }

        if(report.getTicker() == null || report.getTicker().equals("")){
            content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage());
            lines = content.split("\r\n");
            patternTicker = Pattern.compile("(.*)\\s+([A-Z]+)\\s*\\-\\s*(\\$[0-9]+\\.[0-9]+)");
            for (int i = 0; i < lines.length; i++) {
                String line = lines[i];
                Matcher matcherTicker = patternTicker.matcher(line);
                if (matcherTicker.find()) {
                    report.setCompanyName(matcherTicker.group(1));
                    report.setTicker(matcherTicker.group(2));
                    break;
                }
            }
        }

        if(report.getTicker() == null || report.getTicker().equals("")){
            content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage());
            lines = content.split("\r\n");
            patternTicker = Pattern.compile("(.*)\\s+([A-Z]+)\\s*:\\s*(\\$[0-9]+\\.[0-9]+)");
            for (int i = 0; i < lines.length; i++) {
                String line = lines[i];
                Matcher matcherTicker = patternTicker.matcher(line);
                if (matcherTicker.find()) {
                    report.setCompanyName(matcherTicker.group(1));
                    report.setTicker(matcherTicker.group(2));
                    break;
                }
            }
        }

        //Rating
        if(report.getRating() == null || report.getRating().equals("")){
            content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage());
            lines = content.split("\r\n");
            Pattern patternRating = Pattern.compile("(.*)\\s*Price\\sTarget:\\s*\\$[0-9]+");
            for (int i = 0; i < lines.length; i++) {
                String line = lines[i];
                Matcher matcherTicker = patternRating.matcher(line);
                if (matcherTicker.find()) {
                    report.setRating(matcherTicker.group(1));
                    break;
                }
            }
        }

        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(),false);
        lines = content.split("\r\n");
        //Analyst name
        Pattern patternTel = Pattern.compile("(.*)\\s*[0-9]{3}\\-[0-9]+\\-[0-9]+");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();
            if(StringUtil.isEmpty(line))
                continue;
            Matcher matcherName = patternTel.matcher(line);
            if (matcherName.find()) {
                String originName = matcherName.group(1);
                if(StringUtil.isEmpty(originName.trim())){
                    report.addAnalystName(lines[ i - 1]);
                }
                else if(!originName.contains("ThinkEquity Sales") && !originName.contains("Sales") && !originName.contains("Trading")){
                    report.addAnalystName(matcherName.group(1));
                }
            }
        }

        content = FileUtil.pdfReaderWithFontsAndColor(report.getFilePath(),report.getStartPage(),report.getStartPage());
        lines = content.split("\r\n");
        //Company Name
        if(report.getCompanyName() == null || report.getCompanyName().equals("")){
            Pattern patternCompany = Pattern.compile("(Arial,Bold\\]<17\\.0>|ArialMT\\-Bold\\]<17\\.0>|TimesNewRoman,Bold\\]<22\\.0>)(.*)");
            String companyName = "";
            for (int i = 0; i < lines.length; i++) {
                String line = lines[i];
                Matcher matcherCompany = patternCompany.matcher(line);
                if (matcherCompany.find()) {
                    System.out.println(line);
                    String originCompany = matcherCompany.group(2);
                    System.out.println("Set company name here111" + originCompany);
                    if(originCompany.contains("[")){
                        int end = originCompany.indexOf("[");
                        companyName += originCompany.substring(0,end);
                    }
                    else{
                        companyName+= originCompany;
                    }
                }
            }
            Pattern pattern = Pattern.compile("(.*)\\([A-Z]+\\)");
            Matcher matcher = pattern.matcher(companyName);
            if(matcher.find()){
                report.setCompanyName(matcher.group(1));
            }
            else{
                report.setCompanyName(companyName);
            }
        }

        if(report.getCompanyName()==null || report.getCompanyName().equals("")){
            content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(),false);
            lines = content.split("\r\n");
            Pattern patternThree = Pattern.compile("(.*)\\(([A-Z]+),\\s*\\$[0-9]+(\\.[0-9]+)?,\\s*([A-Za-z]+)\\)");
            for (int i = 0; i < lines.length; i++) {
                String line = lines[i];
                Matcher matcher = patternThree.matcher(line);
                if (matcher.find()) {
                    report.setCompanyName(matcher.group(1));
                    report.setTicker(matcher.group(2));
                    report.setRating(matcher.group(3));
                    break;
                }
            }
        }

        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getEndPage(),false);
        lines = content.split("\r\n");
        Pattern patternSentence = Pattern.compile("(^[A-Z]+)([a-z]+)([^\r\n\\.]+\r\n)*[^\r\n\\.]*currently[\r\n\\s]+has[\r\n\\s]+a[\r\n\\s]+financial[\r\n\\s]+interest[\r\n]{0,2}([^\r\n\\.]+[\r\n]{0,2})*(\\.\\s|\\.\r\n)?", Pattern.MULTILINE);
        Matcher matcher = patternSentence.matcher(content);
        if (matcher.find()) {
            String sentence = matcher.group().replaceAll("[\r\n]", " ");
            int begin = sentence.indexOf("The analyst(s)");
            if(begin != -1){
                report.addOwnershipDisclosure(sentence.substring(begin));
            }else
                report.addOwnershipDisclosure(sentence);
        }

        if(report.getTicker() == null || report.getTicker().equals("")){
            Pattern patternTwo = Pattern.compile("([A-Z]+)\\s*\\$[0-9]+(\\.[0-9]+)?\\s*([A-Za-z]+)");
            for (int i = 0; i < lines.length; i++) {
                String line = lines[i];
                Matcher matcherTwo = patternTwo.matcher(line);
                if(matcherTwo.find()){
                    report.setTicker(matcherTwo.group(1));
                    report.setRating(matcherTwo.group(3));
                }
            }
        }

        report.setPriorRecommendation("");
        System.out.println(JSON.toJSON(report));
    }

    public static void process(String rootDir, String resultPath) {
        List<AnalysisReport> reports = new ArrayList<>();
        File[] Files = new File(rootDir).listFiles();
        for (File file : Files) {
            if(file.getName().endsWith(".pdf"))
                reports.addAll(getAnalysisReportPageInfo(file.getPath()));
        }

        //以下代码为写入excel
        List<String> headers = new ArrayList<>();
        headers.add("Date");
        headers.add("Broker name");
        headers.add("Analyst name");
        headers.add("Company name");
        headers.add("Ticker");
        headers.add("Exchange");
        headers.add("Rating");
        headers.add("Initiating Coverage");
        headers.add("Prior recommendation");
        headers.add("Ownership disclosure");
        headers.add("PDF file name");
        headers.add("StartPage");
        headers.add("EndPage");
        SheetModel sheetModel = FileUtil.makeSheet(resultPath, "result", headers);

        List<String[]> data = new ArrayList<>();
        for (AnalysisReport report : reports) {
            try {
                getAnalysisReportDetail(report);
            } catch (Exception e) {
                System.out.println(JSON.toJSON(report));
                e.printStackTrace();
                continue;
            }

            String[] line = new String[]{report.getDate(),
                    report.getBrokerName(),
                    JSON.toJSONString(report.getAnalystNames()),
                    report.getCompanyName(),
                    report.getTicker(),
                    report.getExchange(),
                    report.getRating(),
                    report.getInitiatingCoverage(),
                    report.getPriorRecommendation(),
                    JSON.toJSONString(report.getOwnershipDisclosures()),
                    report.getFileName(),
                    report.getStartPage() + "",
                    report.getEndPage() + ""};
            data.add(line);
        }

        FileUtil.exportSheet(sheetModel.getSheet(), data);
        FileUtil.closeSheet(sheetModel);
        System.out.println("Success!");
    }
}
